package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.HttpClientUtil;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.DictInfoBiz;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.entity.DictInfo;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.threadUtil.ThreadUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: uajuan.wang
 * @Date: 2018/12/10 13:03
 * @Description: 故障分类action
 */
@Controller
@RequestMapping("/web/admin/dictInfo")
public class DictInfoManagerAction {
    Logger logger = LoggerFactory.getLogger(DictInfoManagerAction.class);
    @Autowired
    private DictInfoBiz dictInfoBiz;
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private HttpServletRequest httpServletRequest;

    private Workbook wb;
    private Sheet sheet;
    private Row row;

    @RequestMapping("/list")
    public ModelAndView list() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/dictInfo/dictInfoList");

        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "propertyNameLike", required = false) String propertyNameLike,
                               @RequestParam(value = "propertyCodeLike", required = false) String propertyCodeLike,
                               @RequestParam(value = "typeNameLike", required = false) String typeNameLike,
                               @RequestParam(value = "typeCodeLike", required = false) String typeCodeLike,
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                               HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("propertyNameLike", propertyNameLike);
        queryParam.getSqlMap().put("propertyCodeLike", propertyCodeLike);
        queryParam.getSqlMap().put("typeNameLike", typeNameLike);
        queryParam.getSqlMap().put("typeCodeLike", typeCodeLike);
        if (StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        return dictInfoBiz.findJSONList(queryParam);
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(String id) {

        ModelAndView modelAndView = new ModelAndView();
        DictInfo dictInfo = dictInfoBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("dictInfo", dictInfo);
        modelAndView.setViewName("pages/admin/dictInfo/dictInfoEditPart");

        return modelAndView;
    }

    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(DictInfo dictInfo, HttpServletRequest request
    ) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise == null) {
            return ResultUtil.error("登陆过期，请重新登录");
        }
        dictInfo.setEnterprise(enterprise);
        dictInfoBiz.addOrUpdate(dictInfo);
        return ResultUtil.success();
    }

    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String id) {
        dictInfoBiz.deleteLogic(dictInfoBiz.findModel(StringConverters.null2Long(id)));
        return ResultUtil.success();
    }

    /**
     * 获取数据字典-选择框
     */
    @RequestMapping("/getTroubleCatListMagic")
    @ResponseBody
    public List<SelectVO> getTroubleCatListMagic(@RequestParam(value = "q", required = false) String q,
                                                 @RequestParam(value = "id", required = false) String id) {
        List<SelectVO> selectVOS = new ArrayList<>();
        DictInfo dictInfo = dictInfoBiz.findModel(StringConverters.ToLong(id));
        if (dictInfo != null) {
            selectVOS.add(new SelectVO(dictInfo.getPropertyName(), dictInfo.getId() + ""));
        }
        QueryParam queryParam = new QueryParam(1, 20);
        queryParam.getSqlMap().put("magicLike", q);
        queryParam.getSqlMap().put("magicId", id);
        queryParam.getSqlMap().put("typeCode", q);
        List<DictInfo> dictInfoList = dictInfoBiz.findList(queryParam);
        dictInfoList.forEach(dictInfo1 -> selectVOS.add(new SelectVO(dictInfo1.getPropertyName(), dictInfo1.getId() + "")));
        return selectVOS;
    }

    /**
     * 获取某某类型的数据字典列表
     *
     * @param q
     * @param id
     * @return
     */
    @RequestMapping("/getDictInfoListMagic")
    @ResponseBody
    public List<SelectVO> getDictInfoMagic(@RequestParam(value = "q", required = false) String q,
                                           @RequestParam(value = "id", required = false) String id,
                                           @RequestParam(value = "typeCode", required = false) String typeCode
    ) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(httpServletRequest);

       return dictInfoBiz.getDictInfoMagic( enterprise.getId() + "",q,id,typeCode);
    }


    @RequestMapping("/uploadDictInfoImportFile")
    @ResponseBody
    public ResultDto uploadDictInfoImportFile(HttpServletRequest request,
                                              @RequestParam(value = "file", required = false) MultipartFile file) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null == enterprise) {
            return ResultUtil.error("当前用户企业信息有误，请退出重新登录");
        }
        if (null != file && !file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            String ext = fileName.substring(fileName.lastIndexOf("."));
            try {
                InputStream is = file.getInputStream();
                if (".xls".equals(ext)) {
                    wb = new HSSFWorkbook(is);
                } else if (".xlsx".equals(ext)) {
                    wb = new XSSFWorkbook(is);
                } else {
                    return ResultUtil.error("请导入正确格式的文件（Excel）");
                }
            } catch (Exception e) {
                logger.error("IOException", e);
                return ResultUtil.error("导入失败，请刷新后重试");
            }
        }
        ResultDto resultDto = dictInfoBiz.checkData(wb,enterprise);
        if (resultDto.getStatus() != 0) {
            return resultDto;
        }
        ThreadUtils.importDictThread(dictInfoBiz,wb,enterprise);
        return ResultUtil.success();
    }

    @RequestMapping("/importPage")
    public ModelAndView importPage(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise", enterprise);
        modelAndView.setViewName("pages/admin/dictInfo/import");
        return modelAndView;
    }
}
